package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    WeChatProperties weChatProperties;

    @Resource
    JwtProperties jwtProperties;

    @Resource
    UserMapper userMapper;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //生成openId
        String openId = getOpenId(userLoginDTO.getCode());
        User user = userMapper.selectByOpenId(openId);
        if(user==null){
            //新用户
            user=new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);    //注意主键返回
        }
        //生成token
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //封装UserLoginVO并返回
        return UserLoginVO.builder()
                .id(user.getId())
                .openid(openId)
                .token(token)
                .build();
    }

    private String getOpenId(String code) {
        String url="https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        String jsonData=HttpClientUtil.doGet(url, paramMap);    //返回的是一个json格式的字符串
        JSONObject jsonObject = JSON.parseObject(jsonData);
        return (String) jsonObject.get("openid");
    }
}